import time

from selenium import webdriver
from time import sleep

from selenium.webdriver.common.by import By
import time,datetime

# #实现无可视化操作
# from selenium.webdriver.chrome.options import Options
# #实现规避检测
# from selenium.webdriver import ChromeOptions
#
# #实现无可视化界面的操作
# chrome_options = Options()
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--disable-gpu')
#
# #实现让selenium规避被检测到的风险
# option = ChromeOptions()     #实例化一个ChromeOptions对象
# option.add_experimental_option('excludeSwitches', ['enable-automation'])  #以键值对的形式加入参数

def login():
    bro.get('https://www.taobao.com/')
    if bro.find_element(By.XPATH, r'/html/body/div[1]/div[1]/div/ul[1]/li[2]/div[1]/div[1]/a[1]').click():
        bro.find_element(By.XPATH, r'/html/body/div[1]/div[1]/div/ul[1]/li[2]/div[1]/div[1]/a[1]').click()
        print('请在15秒内登录！')
        time.sleep(15)



    now = datetime.datetime.now()
    print('登录成功,当前时间为',now.strftime("%Y-%m-%d-%H-%M-%S-%f"))

    bro.get('https://cart.taobao.com/cart.htm?spm=a21bo.jianhua.1997525049.1.5af911d9lIvFN6&from=mini&ad_id=&am_id=&cm_id=&pm_id=1501036000a02c5c3739')
    time.sleep(5)

def buy(times):
    while True:
        now = datetime.datetime.now().now().strftime("%Y-%m-%d-%H-%M-%S-%f")
        if now > times:
            #给全选加一个异常捕获
            while True:
                try:
                    if bro.find_element(By.XPATH,r'//*[@id="J_SelectAll1"]/div/label'):
                        bro.find_element(By.XPATH, r'//*[@id="J_SelectAll1"]/div/label').click()
                        break
                except:
                    print('找不到全选按钮')
            sleep(1)
            while True:
                try:
                    if bro.find_element(By.LINK_TEXT,'结 算'):
                        bro.find_element(By.LINK_TEXT,'结 算').click()
                        break
                except:
                    print('找不到结算按钮')
            while True:
                try:
                    if bro.find_element(By.XPATH,r'//*[@id="submitOrderPC_1"]/div[1]/a[2]'):
                        bro.find_element(By.XPATH, r'//*[@id="submitOrderPC_1"]/div[1]/a[2]').click()
                        break
                except:
                    print('找不到提交订单按钮')

if __name__ == '__main__':
    times = input('请输入抢购时间，格式为：2022-10-12 12：15：47-612307')
    #times = '2022-10-12 12：15：47-612307'
    bro = webdriver.Chrome()
    login()
    time.sleep(15)
    buy(times)




